const Router = require('koa-router')
const { ChatHistory } = require('../models')
const auth = require('../middleware/auth')
const { Op } = require('sequelize')

const router = new Router({ prefix: '/system' })

// 获取Token使用统计
router.get('/token-stats', auth.checkPermission('system:manage'), async (ctx) => {
  try {
    const { startDate, endDate } = ctx.query
    
    // 设置默认时间范围（最近30天）
    const now = new Date()
    const defaultStart = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
    const start = startDate ? new Date(startDate) : defaultStart
    const end = endDate ? new Date(endDate) : now

    console.log('📊 获取Token统计数据:', { start: start.toISOString(), end: end.toISOString() })

    // 查询时间范围内的聊天记录
    const chatRecords = await ChatHistory.findAll({
      where: {
        created_at: {
          [Op.between]: [start, end]
        }
      },
      attributes: ['token_usage', 'created_at', 'session_id'],
      raw: true
    })

    console.log('📝 找到聊天记录数量:', chatRecords.length)

    // 计算总Token数
    const totalTokens = chatRecords.reduce((sum, record) => {
      return sum + (record.token_usage || 0)
    }, 0)

    // 计算会话数量（去重）
    const uniqueSessions = new Set(chatRecords.map(record => record.session_id))
    const sessionsCount = uniqueSessions.size

    // 计算平均每会话Token数
    const averageTokensPerSession = sessionsCount > 0 ? Math.round(totalTokens / sessionsCount) : 0

    // 计算总成本（假设1000 tokens = $0.001）
    const totalCost = totalTokens * 0.000001

    // 按日统计
    const dailyStats = {}
    chatRecords.forEach(record => {
      const date = new Date(record.created_at).toISOString().split('T')[0]
      if (!dailyStats[date]) {
        dailyStats[date] = {
          date,
          tokens: 0,
          cost: 0,
          messages: 0
        }
      }
      dailyStats[date].tokens += record.token_usage || 0
      dailyStats[date].cost += (record.token_usage || 0) * 0.000001
      dailyStats[date].messages += 1
    })

    // 转换为数组并排序
    const dailyUsage = Object.values(dailyStats)
      .sort((a, b) => new Date(a.date) - new Date(b.date))

    const responseData = {
      totalTokens,
      totalCost: parseFloat(totalCost.toFixed(6)),
      sessionsCount,
      averageTokensPerSession,
      dailyUsage
    }

    console.log('✅ Token统计数据:', responseData)

    ctx.body = {
      success: true,
      message: '获取Token统计成功',
      data: responseData
    }

  } catch (error) {
    console.error('❌ 获取Token统计失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取Token统计失败',
      error: error.message
    }
  }
})

// 获取系统信息
router.get('/info', auth.checkPermission('system:manage'), async (ctx) => {
  try {
    const info = {
      version: '1.0.0',
      environment: process.env.NODE_ENV || 'development',
      uptime: process.uptime(),
      timestamp: new Date().toISOString()
    }

    ctx.body = {
      success: true,
      message: '获取系统信息成功',
      data: info
    }
  } catch (error) {
    console.error('❌ 获取系统信息失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取系统信息失败',
      error: error.message
    }
  }
})

module.exports = router
